﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Configuration.Provider;

namespace Kis2012.Models
{
    public class CustomRoleProvider : RoleProvider
    {

        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
   
            if (name == null || name.Length == 0)
            {
                name = "CustomRoleProvider";
            }

            if (String.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "Custom Role Provider");
            }

            base.Initialize(name, config);
  
            _AppName = GetConfigValue(config["applicationName"], System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);  
        }

        private string GetConfigValue(string configValue, string defaultValue)
        {
            if (String.IsNullOrEmpty(configValue))
            {
                return defaultValue;
            }
            return configValue;
        }

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            RoleTable roles = new RoleTable();
            UserRolesTable userroles = new UserRolesTable();
            foreach (var role in roleNames)
            {
                if (!RoleExists(role))
                {
                    roles.RegisterRole(role);
                }
                else
                {
                    foreach(var user in usernames) {
                        if (!IsUserInRole(user, role))
                        {
                            userroles.RegisterUserRole(user, role, _AppName);
                        }
                    }
                }
            }
        }

        private string _AppName;
        public override string ApplicationName
        {
            get
            {
                return _AppName;
            }
            set
            {
                _AppName = value;
            }
        }

        public override void CreateRole(string roleName)
        {
            RoleTable roles = new RoleTable();
            Role role = roles.GetAllRoles().SingleOrDefault(u => u.RoleName == roleName);
            if (role == null)
                roles.RegisterRole(roleName);
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            if (!RoleExists(roleName))
            {
                throw new ProviderException("Role does not exist.");
            }

            if (throwOnPopulatedRole && GetUsersInRole(roleName).Length > 0)
            {
                throw new ProviderException("Cannot delete a populated role.");
            }

            RoleTable roles = new RoleTable();
            return roles.DeleteRole(roleName);
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            RoleTable roles = new RoleTable();
            //throw new NotImplementedException();
            return new string[0];
        }

        public override string[] GetAllRoles()
        {
            string tmpRoleNames = "";
            RoleTable roles = new RoleTable();
            
            foreach (Role r in roles.GetAllRoles()) {
                tmpRoleNames += r.RoleName + ",";
            }
            if (tmpRoleNames.Length > 0)
            {
                // Remove trailing comma.

                tmpRoleNames = tmpRoleNames.Substring(0, tmpRoleNames.Length - 1);
                return tmpRoleNames.Split(',');
            }
            return new string[0];
        }

        public override string[] GetRolesForUser(string username)
        {
            string tmpRoleNames = "";
            UserRolesTable roles = new UserRolesTable();

            foreach (UserRoles r in roles.GetRolesByName(username, ApplicationName))
            {
                tmpRoleNames += r.RoleName + ",";
            }
            if (tmpRoleNames.Length > 0)
            {
                // Remove trailing comma.
                tmpRoleNames = tmpRoleNames.Substring(0, tmpRoleNames.Length - 1);
                return tmpRoleNames.Split(',');
            }
            return new string[0];
        }

        public override string[] GetUsersInRole(string roleName)
        {
            string tmpRoleNames = "";
            UserRolesTable roles = new UserRolesTable();

            foreach (UserRoles r in roles.GetUsersByRole(roleName,ApplicationName))
            {
                tmpRoleNames += r.UserName + ",";
            }
            if (tmpRoleNames.Length > 0)
            {
                // Remove trailing comma.
                tmpRoleNames = tmpRoleNames.Substring(0, tmpRoleNames.Length - 1);
                return tmpRoleNames.Split(',');
            }
            return new string[0];
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            UserRolesTable userRolesTable = new UserRolesTable();

            return userRolesTable.IsUserInRole(username, roleName, ApplicationName);
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            UserRolesTable userRolesTable = new UserRolesTable();
            foreach (var Role in userRolesTable.GetAllRoles())
            {
                userRolesTable.DeleteUserFromRole(Role.UserName, Role.RoleName, _AppName);
            }
        }

        public override bool RoleExists(string roleName)
        {
            RoleTable roles = new RoleTable();
            Role role = roles.GetAllRoles().SingleOrDefault(u => u.RoleName == roleName);
            return (role != null);
        }
    }
}